package com.hx.myblog3.control.anon;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hx.myblog3.entity.Article;
import com.hx.myblog3.entity.ArticleType;
import com.hx.myblog3.entity.Comment;
import com.hx.myblog3.service.ArticleService;
import com.hx.myblog3.service.ArticleTypeService;
import com.hx.myblog3.service.CommentService;

@Controller//返回视图
public class DemoControl {
	@Autowired
	private ArticleTypeService ats;
	@Autowired
	private ArticleService as;
	@Autowired
	private CommentService cs;
	
	/*@RequestMapping("/hi")
    public String hello(Model model) {
		model.addAttribute("title", "thymelesf模板演示");
		model.addAttribute("greet", "hi,大家好！");
		return "demo";
	}*/
	
	@RequestMapping({"/","/index"})
	public String index(Model model){
		List<ArticleType> types=ats.all();
		List<Article> articles=as.findAll();
		model.addAttribute("types", types);
		model.addAttribute("articles", articles);
		return "index";
	}
	
	//
	 @RequestMapping("/article")
	 public String article(@RequestParam("id") Integer id, Model model){
		List<ArticleType> types=ats.all();
		Article article=as.findone(id);
		model.addAttribute("types", types);
	    model.addAttribute("article", article);
	    return "article";
	}
	
   //
	 @RequestMapping("/save")
	 @ResponseBody
	 public String saveComment(HttpServletRequest rep,@RequestParam("article_id") Integer id,Comment comment) {
		 Article a=new Article();
		 a.setId(id);
		 String ip=cs.getIpAddress(rep);
		 comment.setArticle(a);
		 comment.setDate(new Date());
		 comment.setUserIp(ip);
		 cs.save(comment); 
		return "保存成功！";
	}
}
